﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MockEs.Core
{
    public class EsServer
    {
        protected MockEsOption _option;

        protected HttpListener _httpListener;

        protected Thread _httpProccessThread;

        public EsServer(MockEsOption option)
        {
            CheckNotNull(option,nameof(option));  
            this._option = option;

            //init httplister
        }

        /// <summary>
        /// start mock server
        /// </summary>
        public void Start()
        {
            if(PortInUse(Convert.ToInt32(this._option.Port)))
                throw new Exception("port have aleardy!");
            this._httpListener = new HttpListener();
            this._httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            this._httpListener.Prefixes.Add(string.Format("http://{0}:{1}/",this._option.Ip,this._option.Port));
            this._httpProccessThread=new Thread(this.WatchRequest);
            this._httpListener.Start();
            this._httpProccessThread.Start();
        }

        //独立线程处理用户的请求
        private void WatchRequest()
        {
            while (true)
            {
                try
                {
                    //reprsent catch a request
                    var httpContext = this._httpListener.GetContext();


                }
                catch (Exception e)
                {

                }
            }
        }

        #region 私有

        private static bool IpIsCorrectAndCanAccess(MockEsOption option,ref string message)
        {
            CheckNotNull(option,nameof(option));
            //1.if localhost
            if (string.IsNullOrEmpty(option.Ip) || string.IsNullOrEmpty(option.Port))
            {
                message = "Ip or Port not be null";
                return false;
            }
            if (option.Ip.Trim().ToLower() == "localhost")
                option.Ip = "127.0.0.1";
            return true;
        }

        protected static void CheckNotNull(object arg,string argumentName)
        {
            if(arg == null)
                throw new Exception(string.Format("the argumengt {0} can not be null",argumentName));
        }

        protected static bool PortInUse(int port)
        {
            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
            return ipEndPoints.Count(u => u.Port == port) > 0;
        }

        #endregion
    }
}
